'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url agent/setting/pub/linkPlans 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			orderinfo,
			percent,
			total_fee
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		let {
			todayStart,
			todayEnd
		} = vk.pubfn.getCommonTime(new Date());
		let minTotal = 0;
		let maxTotal = 0;
		let rule = 0;
		var num = 0;
		var backhaulArry = percent.backhaulArry || 0;
		var OrderNum = 0;
		var douyin_ReturnRatio = 0;
		var douyin_UnReturnRatio = 0;
		var hour_backhaul=percent.hour_backhaul||0;
		var firstorder =percent.firstorder;
		var newuser = percent.newuser; //是否仅回传当日新用户的订单
		if (!orderinfo.promotion_id) {
			res.msg = "该笔订单没有计划id"
			return res;
		}
		try {
			num = await vk.baseDao.count({
				dbName: "a_plans_backhaul", // 表名
				whereJson: { // 条件
					tfid: orderinfo.tfid,
					promotion_id: orderinfo.promotion_id
				}
			});
		} catch (err) {
			var m = "该笔订单没有计划id";
			res.msg = m;
			return res;
		}
		if (num === 0) {
			let id = await vk.baseDao.add({
				dbName: "a_plans_backhaul", // 表名
				dataJson: { // 需要新增的数据 json格式
					tfid: orderinfo.tfid,
					promotion_id: orderinfo.promotion_id,
					proportion_value: 0
				}
			});
		}
		let addvktest = await db.collection('vk-test').add({
			tips: "执行了计划回传函数75",
			 request_id: event.originalParam.context.requestId
		})
		console.log("orderinfo",orderinfo);
		console.log("percent",percent);
		rule = backhaulArry.find(rule => total_fee >= rule.minAmount && total_fee <= rule.maxAmount);
		// 	let rule;
			// for (let i = 0; i < backhaulArry.length; i++) {
			//     if (total_fee >= backhaulArry[i].minAmount && total_fee <= backhaulArry[i].maxAmount) {
			//         rule = backhaulArry[i];
			//         break;
			//     }
			// }
            console.log("total_fee",total_fee);
			console.log("rule",rule);
			console.log("rule.isBackhaul",rule.isBackhaul);
		if (!rule || rule.isBackhaul === 2) {
			return;
		} else if (rule.isBackhaul === 1) {
			let callRes = await vk.callFunction({
				name: "hedian",
				url: 'client/user/pub/callback',
				data: {
					out_trade_no:orderinfo.out_trade_no, //充值订单号
					total_fee: total_fee, //支付金额
					_add_time: orderinfo._add_time,
					_add_time_str: vk.pubfn.timeFormat(orderinfo._add_time,"yyyy-MM-dd hh:mm:ss")
				},
			});
			let addvktest = await db.collection('vk-test').add({
				tips: "执行了计划回传函数105",
			})
		 
			let addvktest1 = await db.collection('vk-test').add({
				tips: "执行了计划回传函数119",
			})
			return;
		}
		minTotal = rule.minAmount
		maxTotal = rule.maxAmount




		let newsday = newuser ? todayStart : new Date().getTime() - 3600000 * hour_backhaul;

		if (
			orderinfo.pay_status === 1 &&
			total_fee > minTotal &&
			total_fee < maxTotal
		) {
			if (firstorder && orderinfo.user_register_date >= newsday && orderinfo
				.is_first === true) {
				OrderNum = updateProportionValue(orderinfo.promotion_id, orderinfo.tfid);
			} else if (!firstorder && orderinfo.user_register_date >= newsday) {
				OrderNum = updateProportionValue(orderinfo.promotion_id, orderinfo.tfid);
			}
		}

		//更新比例数值函数
		async function updateProportionValue(promotion_id, tfid) {
			try {
				let proportion_value = 0;
				await db.collection('a_plans_backhaul').where({
					tfid: tfid,
					promotion_id: promotion_id
				}).update({
					proportion_value: _.inc(1)
				});
				return proportion_value;
			} catch (err) {
				console.log("比例数值错误");
			}
		}


		douyin_ReturnRatio = rule.reportCount;
		douyin_UnReturnRatio = rule.skipCount;
		//计算是否回传
		let RatioSum = Number(douyin_ReturnRatio) + Number(douyin_UnReturnRatio) //比例之和
		console.log("RatioSum", RatioSum);
		if ((OrderNum % RatioSum) <= Number(douyin_ReturnRatio) && (OrderNum % RatioSum) > 0) {
			// 云函数内调用其他云函数或云对象内的函数,进行付费数据回传。
			let callRes = await vk.callFunction({
				name: "hedian",
				url: 'client/user/pub/callback',
				data: {
					out_trade_no:orderinfo.out_trade_no, //充值订单号
					total_fee: total_fee, //支付金额
					_add_time: orderinfo._add_time,
					_add_time_str: vk.pubfn.timeFormat(orderinfo._add_time,"yyyy-MM-dd hh:mm:ss")
				},
			});
		}





		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}